var url = require('../../../../page/common/urlConfig.js')
var QQMapWX = require('../../../../util/qqmap-wx-jssdk.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    second: 60,
    selected: false,
    member_class: ['货车','草商','牧场'],
    member_value: ['truck', 'grass-shops', 'pasture', 'grass-shops', 'mechanics'],
    index: 0,
    member_name:'货车',
    jobId:'',
    openId:'',

    isLogin:false,
    status: '车主',
    province: ['蒙', '京', '津', '沪', '渝', '新', '藏', '宁', '桂', '港', '澳', '黑', '吉', '辽', '晋', '翼', '青', '鲁', '豫', '苏', '皖', '浙', '闽', '赣', '湘',' 奥', '琼', '甘', '陕', '黔', '滇', '川',],
    province_index: 0,
    grassType: ['天然草场', '人工草场', '半人工草场', '割草场'],
    grassType_index: 0,
    grassSize: ['0-10亩', '11-50亩', '51-100亩', '101-500亩', '500亩以上',],
    grassSize_index: 0,
    meadowType: ['温带草原牧场', '山地牧场', '绿洲牧场', '高寒牧场',],
    meadowType_index: 0,
    meadowSize: ['0-10亩', '11-50亩', '51-100亩', '101-500亩', '500亩以上',],
    meadowSize_index: 0,
    params:{},

    member_class_name: '', // 会员类别
    member_name:'',//会员姓名 
    phone_name: '',//电话号码
    grass_shop_name: '', //草商名称
    grass_shop_location: '', //草商地址
    pasture_name:'',//牧场名称
    pasture_address:'',//牧场地址
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    var that=this
    var jobId = getApp().globalData.jobId
    var openId = getApp().globalData.openId
    var isLogin=jobId?true:false
    that.setData({
      'jobId': jobId ? jobId:'',
      'openId': openId ? openId : '',
      'isLogin': isLogin ? isLogin : '',
    })
    if (isLogin){
      //如果用户登录了，那么查询用户信息，并且赋值
      wx.request({
        url: url.queryUserInfoUrl,
        data: { 'entity.identifier': openId},
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        success: function (aa) {
        
          var vo=aa.data.model
          var jobId=vo.jobEntity.identifier
          if (jobId == "grass-shops"){
            that.setData({
              'status': '草商',
              'member_class_name':'草商',
              'member_name': vo.personEntity.personName,
              'grass_shop_name': vo.grassShops.grassShopsName,
              'grass_shop_location': vo.grassShops.positionShortName,
              'phone_name': vo.personEntity.contactNumber ? vo.personEntity.contactNumber:""
            })
          } else if (jobId == "pasture"){
            that.setData({
              'status': '牧场',
              'member_class_name': '牧场',
              'member_name': vo.personEntity.personName,
              'pasture_name': vo.pasture.pastureName,
              'pasture_address': vo.pasture.positionName,
              'phone_name': vo.personEntity.contactNumber ? vo.personEntity.contactNumber : ""
            })
          } else if (jobId == "truck") {
            that.setData({
              'status': '货车',
              'member_class_name': '货车',
              'member_name': vo.personEntity.personName,
              'truck.licensePlate': vo.truck.licensePlate,
              'car_type': vo.truck.truckType,
              'car_length': vo.truck.truckLength,
              'car_weight': vo.truck.loadWeight,
              'pasture_address': vo.truck.newlyPositionName,
              'phone_name': vo.personEntity.contactNumber ? vo.personEntity.contactNumber : ""
            })
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  },

  memberTypePickerChange: function (e) {
   
    console.log('picker发送选择改变，携带值为', e.detail.value)

    var that = this;
  
    var status_name = that.data.member_class[e.detail.value]
    if (status_name=='货车'){
      that.data.params['vo.jobEntity.identifier'] = 'truck'
    } else if (status_name == '草商'){
      that.data.params['vo.jobEntity.identifier'] = 'grass-shops'
    } else if (status_name == '牧场') {
      that.data.params['vo.jobEntity.identifier'] = 'pasture'
    }
    
    that.setData({
      member_class_name: status_name,
      status: status_name
    })


  },
  
  provincePickerChange: function(e){
    var that = this;
    that.data.params['provinceName'] = that.data.province[e.detail.value]
    that.setData({
      province_name: that.data.province[e.detail.value]
    })

  },

  grassTypePickerChange: function(e){
    var that = this;
    that.setData({
      grassType_index: e.detail.value,
    })

  },
  formSubmit: function (e) {
    debugger
    wx.showLoading({
      title: '正在加载',
    })
    var that = this
    var params=that.data.params//参数，参数里面保存的主要是下拉框的
    for (var p in e.detail.value) {//将得到的键值对，赋值给params
      params[p] = e.detail.value[p]
    }
    var code, openId,globalData
    globalData = getApp().globalData
    openId =globalData.openId//d得到openiD
    var userInfo = globalData.userInfo
    //得到用户名和用户性别
    if (userInfo){
      params['entity.username'] = userInfo.nickName
      params['prsonEntity.sexDictCode'] = userInfo.gender
    }else{
      wx.getUserInfo({
        succcess:function(res){
          params['entity.username'] = res.nickName
          params['prsonEntity.sexDictCode'] = res.gender
        }
      })    
    }
    
    params['entity.identifier'] = openId
    if (params['vo.jobEntity.identifier'] =='truck'){
      params['vo.truck.contactsPhone'] = params['personEntity.contactNumber']
    } else if (params['vo.jobEntity.identifier'] == 'pasture'){
      params['vo.pasture.contactsPhone'] = params['personEntity.contactNumber']
    } else if (params['vo.jobEntity.identifier'] == 'grass-shops') {
      params['vo.grassShops.contactsPhone'] = params['personEntity.contactNumber']
    }
    if (!params['entity.username']) {
      params['entity.username'] = params['personEntity.personName']
    }
    if (params['vo.jobEntity.identifier'] =='truck'){
      params['truck.licensePlate'] = params['provinceName']+params['truck.licensePlate']
     
      var demo = new QQMapWX({
        key: 'YQVBZ-QEBCS-5KTOI-6U6TG-4B6RF-ZJFCI'// 必填
      });
      wx.getLocation({
        success: function(res) {
          demo.reverseGeocoder({
            location: {
              latitude: res.latitude,
              longitude: res.longitude,
            },
            success: function (aa) {
              params['truck.newlyPositionName'] =aa.result.address
              params['truck.newlyPositionShortName'] = aa.result.address
              params['truck.newlyCoordinatesX'] = res.latitude
              params['truck.newlyCoordinatesY'] = res.longitude
              wx.request({
                url: url.registUrl,
                data: params,
                header: {
                  "Content-Type": "application/x-www-form-urlencoded"
                },
                method: "POST",
                success: function (res) {
                  if (res.data.model.errorMessage){
                    wx.showToast({
                      title: '注册失败',
                      duration: 2000
                    })
                  }else{
                    getApp().globalData.jobId = params['vo.jobEntity.identifier']
                    getApp().globalData.userId = res.data.model.truck.identifier
                    getApp().globalData.isChangeRegister=true
                    wx.showToast({
                      title: '注册成功',
                      duration: 1000,
                      complete: function (e) {
                        setTimeout((function callback() {
                          wx.hideLoading()
                          wx.navigateBack({
                            url: "../information/information",
                          })
                        }).bind(this), 2000);
                      }
                    })
                  }
                  // 暂时只考虑了很完美的情况
                }
              })
            },
  
          });
        },
      })
    }else{
      wx.request({
        url: url.registUrl,
        data: params,
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        success: function (res) {
          // 暂时只考虑了很完美的情况
          if (cc.data.model.errorMessage) {
            wx.showToast({
              title: '注册失败',
              duration: 2000
            })
          } else {
            getApp().globalData.isChangeRegister = true
            getApp().globalData.jobId = params['vo.jobEntity.identifier']
            if (res.data.model.pasture && res.data.model.pasture.identifier) {
              getApp().globalData.userId = res.data.model.truck.identifier
            } else if (res.data.model.grassShops && res.data.model.grassShops.identifier) {
              getApp().globalData.userId = res.data.model.grassShops.identifier
            }
            wx.showToast({
              title: '注册成功',
              duration: 1000,
              complete: function (e) {
                setTimeout((function callback() {
                  wx.hideLoading()
                  wx.navigateBack({
                    url: "../information/information",
                  })
                }).bind(this), 2000);
              }
            })
          }
        },
        complete: function (e) {
          wx.hideLoading()
        }
      })
    } 
  },
  grassSizePickerChange: function(e){
    var that = this;
    that.setData({
      grassSize_index: e.detail.value,
    })

  },

  meadowTypePickerChange: function (e) {
    var that = this;
    that.setData({
      meadowType_index: e.detail.value,
    })

  },

  meadowSizePickerChange: function (e) {
    var that = this;
    that.setData({
      meadowSize_index: e.detail.value,
    })

  },


  //获取草场地址
  tapGrassAddress: function(e){
    var that = this
    wx.chooseLocation({
      success: function (res) {
        console.log(res)
        that.setData({
          grass_Add_latitude: res.latitude,
          grass_Add_longitude: res.longitude,
          grass_Add: res.address
        });
      }
    });

  },

  //获取牧场地址
  tapMeadowAddress: function (e) {
  

    var that = this
    wx.chooseLocation({
      success: function (res) {
 
        console.log(res)
        that.setData({
          pasture_address: res.address
        });
        that.data.params['pasture.positionName'] = res.address;
        that.data.params['pasture.positionShortName'] = res.name;
        that.data.params['pasture.coordinatesX'] = res.latitude;
        that.data.params['pasture.coordinatesY'] = res.longitude;
      }
    });

  },
  //草商选择位置

  tapMeadowShopsAddress:function(){
    var that = this
    wx.chooseLocation({
      success: function (res) {
        that.setData({
          grass_shop_location: res.address
        });
        that.data.params['grassShops.positionName'] = res.address;
        that.data.params['grassShops.positionShortName'] = res.name;
        that.data.params['grassShops.coordinatesX'] = res.latitude;
        that.data.params['grassShops.coordinatesY'] = res.longitude;
      }
    });

  },
  tapSendMsg: function(e){
    this.setData({
      selected: true,
      // selected1: false,
    });
    countdown(this);
  }


});


function countdown(that) {
  var second = that.data.second;
  if (second == 0) {
    // console.log("Time Out...");
    that.setData({
      selected: false,
      // selected1: true,
      second: 60,
    });
    return;
  }
  var time = setTimeout(function () {
    that.setData({
      second: second - 1
    });
    countdown(that);
  }
    , 1000)
}